package com.price.sample.http

import android.os.Bundle
import android.widget.Button
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.price.common.base.BaseActivity
import com.price.common.extend.logError
import com.price.common.extend.toast
import com.price.sample.http.person.HomeViewModel
import com.zp.common.R


class HttpActivity : BaseActivity() {


    private val homeViewModel: HomeViewModel by viewModels { HomeViewModel.Factory }

    private lateinit var adapter: ArticleAdapter

    override fun getViewId(): Int = R.layout.activity_http

    override fun initView(savedInstanceState: Bundle?) {
        val recyclerView: RecyclerView = findViewById(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = ArticleAdapter()
        recyclerView.adapter = adapter


        findViewById<Button>(R.id.btn_test).setOnClickListener {
            getList()
        }
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun getTest() {
        //同步
//        launch(this) {
//            val it = homeViewModel.getTest1()
//            logError("test callBack:${it}")
//            when (it) {
//                is HttpResult.Success -> {
//                    toast(it.data.toString())
//                }
//
//                is HttpResult.Failure -> {
//                      toast(it.message)
//                }
//            }
//        }
        //异步
//        launchHttp(this, action = {homeViewModel.getTest()}, callBack = {
//            when(it){
//                is HttpResult.Success->{
//                    toast(it.data.toString())
//                }
//                is HttpResult.Failure->{
//                    toast(it.message)
//                }
//            }
//        })

    }

    private fun getList() {
//        launchHttp(this, action = { homeViewModel.getList() }) {
//            when (it) {
//                is HttpResult.Success -> {
//                    adapter.setData(it.data?.datas)
//                }
//
//                is HttpResult.Failure -> {
//                    toast(it.message)
//                }
//            }
//        }


        launchHttp(this, action = { homeViewModel.getList() },
            success = {
                adapter.setData(it?.datas)
        }, fail = { _, msg ->
                toast(msg)
                logError("Error====${msg}")
        })

//        launch(this, action = { homeViewModel.getList() }){
//            logError("====${it.string()}")
//        }
    }


}